<template>
  <div :class="classes" :style="styles" >
    <div class="ifast-carousel-arrow-left" @click="arrowEvent(-1)">
          <Icon :type="iconLeftType" size="20" color="white"></Icon>
    </div>
    <div class="ifast-list">
        <div class="ifast-item" :class="{'heightenZindex':!showCopySwitch}" :style="itemStyle" ref="itemRef">
          <slot></slot>
        </div>
        <div class="ifast-item-cp" :class="{'heightenZindex':showCopySwitch}" ref="itemCp" :style="itemCpStyle"></div>
    </div>
    <div class="ifast-carousel-arrow-right" @click="arrowEvent(1)">
        <Icon :type="iconRightType" size="20" color="white"></Icon>
    </div>
    <ul class="ifast-carousel-dos">
        <li :class="{'active':currentIndex==index,'circularDoc':radiusDot }" v-for="(item,index) in slideInstances" :key="index" 
          @click="dosArrow('click',index)"
          @mouseover="dosArrow('hover',index)"></li>
    </ul>
  </div>
</template>

<script>
let prefixCls='ifast'
import Icon from '../icon/icon';
import { on, off,getStyle } from '../../utils/dom';
import { findComponentsDownward,oneOf } from '../../utils/index';
// 'hover-移入显示','always-一直显示','notArrow-不显示'
//autoplay是否自动播放
//trigger指示器，方形还是圆点
//iconLeftType、iconRightType arrow Icon图形，
//loop 是否无限滚动
export default {
  name: "Carousel",
  props: {
    height:{
      type:[Number,String],
      default:50
    },
    arrow:{
      type:String,
      default:'hover',
      validator(val){
        return oneOf(val,['hover','always','notArrow'])
      }
    },
    autoplay:{
      type:Boolean,
      default:false,
    },
    speed:{
      type:Number,
      default:2000
    },
    loop:{
      type:Boolean,
      default:false
    },
    easing: {
        type: String,
        default: 'ease'
    },
    trigger:{
      type:String,
      default:'click',
      validator(val){
        return oneOf(val,['click','hover'])
      }
    },
    radiusDot:{
      type:Boolean,
      default:false
    },
    iconLeftType:{
      type:String,
      default:'ion-ios-arrow-left'
    },
    iconRightType:{
      type:String,
      default:'ion-ios-arrow-right'
    },
    value:{
      type:Number,
      default:0
    }
  },
 components: {Icon},
  computed: {
    arrowClasses(){
      return [
        `${prefixCls}`
      ]
    },
    classes() {
      return [
       `${prefixCls}-carousel-box`,
       `${prefixCls}-arrow-${this.arrow}`
      ];
    },
    styles(){
      let style={}
      if(this.height){
        style.height=this.height+'px';
      }
      return style;
    },
    listStyle(){
      let style={}
      if(this.height){
        style.height=this.height+'px';
      }
      return style;
    },
    itemStyle(){
      let style={
        width:Number(this.containerWidth)*this.slideInstances.length+'px',
        height:this.height+'px',
        transform: `translate3d(${-this.itemOffsetWidth}px, 0px, 0px)`,
        transition: `transform 500ms ${this.easing}`,
        timer:null,
      }
      return style;
    },
    itemCpStyle(){
      let style={
        width:Number(this.containerWidth)*this.slideInstances.length+'px',
        height:this.height+'px',
        transform: `translate3d(${-this.itemCopyOffsetWidth}px, 0px, 0px)`,
        transition: `transform 500ms ${this.easing}`,
        timer:null,
      }
      return style;
    }
  },
  data() {
    return {
      currentIndex:this.value,
      itemOffsetWidth:0,
      containerWidth:0,
      containerHeight:0,
      childrens: [],
      slideInstances:[],
      timer:null,
      itemIndex:this.value,
      itemCopyIndex:this.value,
      itemCopyOffsetWidth:0,
      showCopySwitch:false,
      hideTrackPos:-1
    };
  },

  methods: {
    arrowEvent(index){
      this.add(index)
      this.setAutoplay()
    },
    add(off){
      
      let slideLength=this.slideInstances.length;
      let oldIndex=this.currentIndex;
      let index=oldIndex+off;
      //处理无现滚动元素距离 单位
      while(index<0) index+=slideLength;
      //初始化
      if(this.loop){
        if(off>0){
          this.hideTrackPos=-1;
        }else{
          this.hideTrackPos=slideLength;
        }
        if (this.showCopySwitch) {
            this.itemIndex=this.hideTrackPos;
          }else{
            this.itemCopyIndex = this.hideTrackPos;
          } 
      }
      //处理临界值，第一个、最后一个切换处理
      if(((off > 0 && index === slideLength) || (off < 0 && index === slideLength - 1)) && this.loop){
         this.showCopySwitch=!this.showCopySwitch;
         this.itemIndex += off;
         this.itemCopyIndex += off;
      }else{
        if(this.showCopySwitch){
          this.itemCopyIndex=index;
        }else{
          this.itemIndex = index;
        }
      }
      this.currentIndex = index === slideLength ? 0 : index;
      this.$emit('input', this.currentIndex);
      this.$emit('on-change', this.currentIndex);
    },
    
    slideInt(){
     this.childrens=findComponentsDownward(this,'CarouselItem');
     this.slideInstances=[];
     this.childrens.map((clildre)=>{
       clildre.height=this.height;
       clildre.width=this.containerWidth;
       this.slideInstances.push(clildre.$el);
     })
     //  给默认值
     this.itemCopyIndex=this.slideInstances.length-this.currentIndex;
    },
    containerResize(){
      this.containerWidth=getStyle(this.$el,'width').replace('px','');
      this.slideInt();
    },
    slotChange () {
        this.$nextTick(() => {
            console.log('slotChange')
            this.slides = [];
            this.slideInstances = [];
            this.slideInt();
            // this.updatePos();
            // this.updateOffset();
        });
    },
    setAutoplay(){
      window.clearInterval(this.timer);
      if(this.autoplay){
        this.timer=setInterval(()=>{
            this.add(1);
        },this.speed)
      }
     
    },
    //需要手动更新的时候
    updateItemIndex (index) {
        if (this.showCopySwitch) {
            this.itemCopyIndex = index;
        } else {
            this.itemIndex = index;
        }
        this.currentIndex = index;
    },
    updateOffset () {
        this.$nextTick(() => {
            //处理切换无限滚动时1px间隙
            let f = this.itemCopyIndex > 0 ? -1 : 1;
            this.itemOffsetWidth=this.itemIndex*this.containerWidth;
            this.itemCopyOffsetWidth=this.itemCopyIndex*this.containerWidth+f;
        });
    },
    // copy Dom
    itemCopyDom () {
        this.$nextTick(() => {
            this.$refs.itemCp.innerHTML=this.$refs.itemRef.innerHTML;
        });
    },
    dosArrow(event,index){
      if(event===this.trigger){
        this.updateItemIndex(index);
        this.setAutoplay();
        this.$emit('input', index);
      }
    }
  },
  mounted(){
    this.containerResize();
    this.slideInt();
    this.updateOffset();
    this.setAutoplay();
    on(window, 'resize', this.containerResize);
  },
  beforeDestroy () {
      off(window, 'resize', this.containerResize);
  },
  watch:{
    itemIndex(){
      this.updateOffset();
    },
    itemCopyIndex(){
      this.updateOffset();
    },
    currentIndex(){
      this.updateOffset();
    },
    copyTrackIndex () {
        this.updateOffset();
    },
    height () {
        this.updatePos();
    },
    value (val) {
       this.updateItemIndex(val)
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
